(function() {
    // Configuration
    const IMAGE_PATH = './assets/git.gif'; 
    const IMAGE_HEIGHT = '80px'; 
    
    // Create road element (UI simulation)
    const road = document.createElement('div');
    // Style the road
    Object.assign(road.style, {
        position: 'fixed',
        bottom: '0',
        left: '-10%',
        width: '120%',
        height: '60px', // Increased height
        backgroundColor: '#374151', // Dark gray road surface
        // Create dashed line using gradient for animation
        backgroundImage: 'linear-gradient(90deg, transparent 50%, rgba(255, 255, 255, 0.8) 50%)', // Brighter lines
        backgroundSize: '150px 10px', // Thicker and longer dashes for better sharpness
        backgroundRepeat: 'repeat-x',
        backgroundPosition: '0 center', // Centered vertically
        zIndex: '9998', // Behind the character
        pointerEvents: 'none',
        // 3D Perspective - Adjusted to reduce blur
        // Increased perspective value (less extreme distortion)
        // Removed scale, adjusted rotateX
        transform: 'perspective(800px) rotateX(60deg)',
        transformOrigin: 'bottom center',
        boxShadow: '0 -10px 20px rgba(0,0,0,0.5)', // Stronger shadow
        // Force GPU acceleration and better rendering
        backfaceVisibility: 'hidden',
        webkitFontSmoothing: 'antialiased'
    });

    // Create image element
    const img = document.createElement('img');
    img.src = IMAGE_PATH;
    img.alt = 'Scroll Progress Character';
    
    // Apply styles to image
    Object.assign(img.style, {
        position: 'fixed',
        bottom: '0', // Slightly above the road
        left: '0',
        height: IMAGE_HEIGHT,
        zIndex: '9999', // Top layer
        pointerEvents: 'none',
        transition: 'left 0.1s linear', // Smooth movement, instant flip
        willChange: 'left, transform' // Optimize rendering
    });
    
    // Handle loading
    img.onload = function() {
        document.body.appendChild(road);
        document.body.appendChild(img);
        updatePosition();
    };
    
    img.onerror = function() {
        console.warn('Scroll character image not found.');
    };

    let ticking = false;
    let lastScrollTop = window.scrollY || document.documentElement.scrollTop;

    function updatePosition() {
        const scrollTop = window.scrollY || document.documentElement.scrollTop;
        const docHeight = document.documentElement.scrollHeight;
        const winHeight = window.innerHeight;
        const maxScroll = docHeight - winHeight;
        
        if (maxScroll <= 0) {
            img.style.left = '0px';
            return;
        }

        // Direction detection and Flip logic
        // We use a small threshold to prevent flickering on tiny scroll bounces
        if (Math.abs(scrollTop - lastScrollTop) > 1) { 
            if (scrollTop > lastScrollTop) {
                // Scrolling Down -> Moving Right -> Face Right (Normal)
                img.style.transform = 'scaleX(1)';
            } else {
                // Scrolling Up -> Moving Left -> Face Left (Flipped)
                img.style.transform = 'scaleX(-1)';
            }
        }
        lastScrollTop = scrollTop;

        // Calculate progress percentage (0 to 1)
        const scrollPercent = Math.max(0, Math.min(1, scrollTop / maxScroll));
        
        // Calculate horizontal position
        const maxLeft = window.innerWidth - (img.offsetWidth || 80); 
        const leftPos = scrollPercent * maxLeft;

        img.style.left = `${leftPos}px`;
        
        // Animate road dashed line
        // Move opposite to scroll direction to simulate speed
        // The factor 0.5 determines the speed of the road movement relative to scroll
        road.style.backgroundPositionX = `${-scrollTop * 0.5}px`;
    }

    // Use requestAnimationFrame for performance
    function onScroll() {
        if (!ticking) {
            window.requestAnimationFrame(function() {
                updatePosition();
                ticking = false;
            });
            ticking = true;
        }
    }

    // Event listeners
    window.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onScroll, { passive: true });
    
    // Initial position
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', updatePosition);
    } else {
        updatePosition();
    }
})();
